package leetcode;

import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;

/**
 * 二分查找
 * 缺点：元素必须先排好序
 *
 * @author TANGYE
 * @2021/1/14 14:53
 */
public class BinSearch {

    public static void main(String[] args) {
        int[] nums = new int[]{1, 2, 4, 6, 9, 10, 15, 19, 22};
        System.out.println(searchByBin(nums, 19));
    }

    public static int searchByBin(int[] nums, int num) {
        if (null == nums || nums.length < 1) {
            return -1;
        }
        int low = 0;
        int high = nums.length - 1;
        int mid;
        int loop = 0;
        while (low <= high) {
            loop++;
            mid = (low + high) / 2;
            if (nums[mid] == num) {
                System.out.println("元素个数：" + nums.length + ", 循环执行次数：" + loop);
                return mid;
            }
            if (nums[mid] > num) {
                high = mid - 1;
            }
            if (nums[mid] < num) {
                low = mid + 1;
            }
        }
        return -1;
    }

}
